package ch.netcetera.planningpoker.server;

import java.util.List;
import java.util.logging.Logger;

import ch.netcetera.planningpoker.server.dao.ParticipantDao;
import ch.netcetera.planningpoker.server.model.Participant;
import ch.netcetera.planningpoker.shared.ui.events.GameUiEvent;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

// TODO serverside dependency injection?
public class ChannelMessageSender {

    private static final Logger logger = Logger
            .getLogger(ChannelMessageSender.class.getName());

    public void sendGameRelatedEvent(GameUiEvent event, Long gameId) {

        String message = event.getChannelMessageForGame(gameId);

        ParticipantDao participantDao = new ParticipantDao();

        ChannelService channelService = ChannelServiceFactory
                .getChannelService();
        List<Participant> participantsForGame = participantDao
                .getParticipantsForGame(gameId);
        for (Participant participant : participantsForGame) {

            logger.info("Pushing msg [" + message + "] by channel api to ["
                    + participant.getName() + "]");

            channelService.sendMessage(new ChannelMessage(participant.getId()
                    + "", message));
        }

    }

}
